package com.v1.video.view;

import java.util.UUID;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.BaseActivity;
import com.v1.video.activity.PaikeVideoDetailActivity2;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ScenarioVideoInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.fragment.ClassifyFragment;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;
import com.v1.video.util.WindowUtils;
import com.v1.video.view.CustomVideoViewNew.SizeChangeLinstener;
/**
 * 视频播放器辅助类
 * @author wangfang
 *
 */
public class VideoPlayerHelper {

	private static final String TAG = "VideoPlayerHelper";
	private static final int sDefaultTimeout = 3000; // 消息延迟时间
	private static final int sPrgTimeout = 1000; // 消息延迟时间
	private static final int sLogTimeout = 5000; // 消息延迟时间
	private static final int FADE_OUT = 1; // 隐藏播放器控制器
	private static final int SHOW_PROGRESS = 2;// 更新播放器控制器进度
	private static final int SHOW_PROGRESS_TWO = 3;// 更新当前播放进度
	private static final int CHECK_NET_WORK_CONNECTION = 4;// 判断网络状态,新版用广播替代
	private static final int SEND_LOG = 5;

	private View mRootView;
	private View mLayShade;
	private TextView mTvTitle;// 视频标题
	private ImageView mIvPlay;// 视频播放按钮
	private TextView mTvBeginTime;// 播放时间
	private TextView mTvEndTime;// 结束时间
	private SeekBar mSeekBar;// 视频带滑动功能的进度条
	private CustomVideoViewNew mVideoView;
	private View mBufferingIndicator;// 缓冲提示容器视图
	private Context mCxt;
	private boolean mShowing = false;// 播放控制器是否显示，true显示，false隐藏
	private TextView mBufferingMsg;// 缓冲提示
	private View mVideoPlayLayout;// 视频容器
	private boolean mPlaying = false;// 视频播放状态,true正在播放,false停止播放。
	private boolean mError = false;// 视频播放异常,true播放异常
	private boolean mDragging = false;// 播放进度条是否滑动,true拖动中,false拖动结束
	private boolean mPause = false;// 是否主动暂停
	private boolean mStop = false;// 是否停止播放
	private String mVideoUri;
	private String mTitle; // 视频标题
	private boolean mRelease = false;
	private String mVid;
	private ClassifyFragment mParentFragment;
	private String mUuid;

	public String getTitle() {
		return mTitle;
	}

	public void setTitle(String mTitle) {
		this.mTitle = mTitle;
	}

	public void setParentFragment(ClassifyFragment parentFragment) {
		this.mParentFragment = parentFragment;
	}

	public VideoPlayerHelper(Context cxt, View rootView) {
		mRelease = false;
		mCxt = cxt;
		mRootView = rootView;
		initView();
	}

	private void initView() {
		if (mRootView != null) {
			mVideoPlayLayout = mRootView.findViewById(R.id.videoPlayLayout);
			mBufferingIndicator = mRootView.findViewById(R.id.waiting_ll);
			mBufferingMsg = (TextView) mRootView.findViewById(R.id.load_rate);
			mVideoView = (CustomVideoViewNew) mRootView
					.findViewById(R.id.vv_videoview);
			mVideoView.setVisibility(View.VISIBLE);
			mLayShade = mRootView.findViewById(R.id.lay_shade);
			mTvTitle = (TextView) mRootView.findViewById(R.id.tv_title);
			mIvPlay = (ImageView) mRootView.findViewById(R.id.iv_playstate);
			mTvBeginTime = (TextView) mRootView.findViewById(R.id.tv_begintime);
			mTvEndTime = (TextView) mRootView.findViewById(R.id.tv_endtime);
			mSeekBar = (SeekBar) mRootView.findViewById(R.id.seekBar);
			mSeekBar.setProgress(0);
			mVideoView.setMediaBufferingIndicator(mBufferingIndicator);
			mBufferingIndicator.setVisibility(View.VISIBLE);
			mIvPlay.setVisibility(View.GONE);
			mRootView.findViewById(R.id.iv_zoom).setOnClickListener(
					onClickListener);
			mVideoView.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					// TODO Auto-generated method stub
					Logger.i(TAG, "OnPreparedListener()");
					if (mVideoView == null)
						return;
					int duration = mVideoView.getDuration();
					mSeekBar.setMax(duration);
					mTvBeginTime.setText(Utils.millisToString(0));
					mTvEndTime.setText(Utils.millisToString(duration));
					show();
					mBufferingIndicator.setVisibility(View.GONE);
					videoPlayUpToServer("0","0");
				}
			});
			mVideoView
					.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

						@Override
						public void onBufferingUpdate(MediaPlayer mp,
								int percent) {
							// TODO Auto-generated method stub
							Logger.i(TAG, "OnBufferingUpdateListener()");
						}
					});
			mVideoView.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					Logger.i(TAG, "OnTouchListener()");
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						if (!mError)
							toggleMediaControlsVisiblity();
					}
					return true;
				}
			});
			mVideoView.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					Logger.i(TAG, "OnCompletionListener()");
					if (mVideoView == null)
						return;
					mSeekBar.setProgress(0);
					mHandler.removeMessages(SHOW_PROGRESS_TWO);
					mIvPlay.setImageResource(R.drawable.icon_play_mini);
					mPlaying = false;
					videoPlayUpToServer("2", mVideoView.getDuration() / 1000
							+ "");
				}
			});
			mVideoView.setOnErrorListener(new OnErrorListener() {

				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					// TODO Auto-generated method stub
					Logger.i(TAG, "OnErrorListener()");
					Logger.i(TAG, "what=" + what + ",extra=" + extra);
					try {
						mHandler.removeMessages(SHOW_PROGRESS_TWO);
						if (mVideoView != null) {
							switch (extra) {// extra的错误码很奇怪，没有匹配的，基本上都走default
							case MediaPlayer.MEDIA_ERROR_IO:
								mTvTitle.setText("视频源或网络错误");
								Toast.makeText(mCxt, "视频源或网络错误",
										Toast.LENGTH_SHORT).show();
								Message msg = mHandler
										.obtainMessage(CHECK_NET_WORK_CONNECTION);
								mHandler.sendMessageDelayed(msg,
										sDefaultTimeout);
								break;
							case MediaPlayer.MEDIA_ERROR_MALFORMED:
								mTvTitle.setText("视频编码或文件错误");
								Toast.makeText(mCxt, "视频编码或文件错误",
										Toast.LENGTH_SHORT).show();
								break;
							case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
								mTvTitle.setText("视频格式不支持");
								Toast.makeText(mCxt, "视频格式不支持",
										Toast.LENGTH_SHORT).show();
								break;
							case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
								if (mVideoView != null) {
									// 设置播放视频源的路径
									Uri videoUri = Uri
											.parse("http://f01.v1.cn/group1/M00/19/87/ChQBFVUCjQqAN-88AZsyqcNCIEM984.mp4");
									mVideoView.setVideoURI(videoUri);
									mTvTitle.setText("视频请求超时，正在重新请求");
									Toast.makeText(mCxt, "视频请求超时，正在重新请求",
											Toast.LENGTH_SHORT).show();
								}
								break;
							default:
								mTvTitle.setText("视频播放未知错误");
								Toast.makeText(mCxt, "视频播放未知错误",
										Toast.LENGTH_SHORT).show();
								break;
							}
							if (MediaPlayer.MEDIA_ERROR_TIMED_OUT != extra) {
								mVideoView.stopPlayback();
								Log.i("MyVideo", "vv.getCurrentPosition():"
										+ mVideoView.getCurrentPosition());
								mHandler.removeMessages(FADE_OUT);
								mHandler.removeMessages(SHOW_PROGRESS);
								mHandler.removeMessages(SEND_LOG);
								mShowing = true;
								mPlaying = false;
								mError = true;
								mBufferingIndicator.setVisibility(View.GONE);
								mSeekBar.setOnSeekBarChangeListener(null);
								mIvPlay.setImageResource(R.drawable.icon_play_mini);
								mLayShade.setVisibility(View.VISIBLE);
							}
						}
						return true;
					} catch (Exception ex) {
						Logger.i(TAG, ex.getMessage());
						return true;
					}
				}
			});
			mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
				public void onStartTrackingTouch(SeekBar bar) {
					show(3600000);
					mDragging = true;
					mHandler.removeMessages(SHOW_PROGRESS);
					mHandler.removeMessages(SEND_LOG);
				}

				public void onProgressChanged(SeekBar bar, int progress,
						boolean fromuser) {
					if (fromuser) {
						mVideoView.seekTo(progress);
						mTvBeginTime.setText(Utils.millisToString(progress));
					}
				}

				public void onStopTrackingTouch(SeekBar bar) {
					mDragging = false;
					show(sDefaultTimeout);
					mHandler.sendEmptyMessage(SHOW_PROGRESS);
					mHandler.sendEmptyMessage(SEND_LOG);
				}
			});
			mIvPlay.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Logger.i(TAG, "OnClickListener() 视频播放或停止");
					if (mPlaying) {
						mStop = true;
						mVideoView.pause();
						mIvPlay.setImageResource(R.drawable.btn_play_video);
						mPlaying = false;
					} else {
						mStop = false;
						if (!Helper.checkConnection(mCxt)) {
							mShowing = true;
							mLayShade.setVisibility(View.VISIBLE);
							mTvTitle.setText("视频源或网络错误");
						} else {
							if (!mError) {
								mVideoView.start();
								mIvPlay.setImageResource(R.drawable.btn_play_video_pause);
								mPlaying = true;
							} else {
								resetVideoView();
							}
						}
					}
				}
			});
			mVideoView.setSizeChangeLinstener(new SizeChangeLinstener() {

				@Override
				public void doMyThings() {
					// TODO Auto-generated method stub
//					setVideoPlayerSize();
				}
			});
			Logger.i(TAG, "initView()");
			mUuid = UUID.randomUUID().toString();
		}
	}

	public void setVid(String mVid) {
		this.mVid = mVid;
	}

	/**
	 * 设置视频源
	 * 
	 * @param uri
	 */
	public void setVideoURI(String videoUri) {
		mVideoUri = videoUri;
		mSeekBar.setProgress(0);
	}

	/**
	 * 开始播放
	 */
	public void start() {
		if (!Helper.checkConnection(mCxt)) {
			mError = true;
			mShowing = true;
			mTvTitle.setText("视频源或网络错误");
			mLayShade.setVisibility(View.VISIBLE);
		} else {
			if (!mStop) {
				resetVideoView();
			}
		}
	}
	
	public boolean isStop() {
		return mStop;
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int pos;
			if (mRelease) {
				return;
			}
			switch (msg.what) {
			case FADE_OUT:
				hide();
				break;
			case SHOW_PROGRESS:
				pos = setProgress();
				if (!mDragging && mVideoView.isPlaying()) {
					msg = obtainMessage(SHOW_PROGRESS);
					sendMessageDelayed(msg, sDefaultTimeout);
				}
				break;
			case SHOW_PROGRESS_TWO:
				pos = mVideoView.getCurrentPosition();
				msg = obtainMessage(SHOW_PROGRESS_TWO);
				sendMessageDelayed(msg, sPrgTimeout);
				break;
			case CHECK_NET_WORK_CONNECTION:
				if (Helper.checkConnection(mCxt)) {
					resetVideoView();
				} else {
					msg = obtainMessage(CHECK_NET_WORK_CONNECTION);
					sendMessageDelayed(msg, sDefaultTimeout);
				}
				break;
			case SEND_LOG:
				if (!mDragging && mVideoView.isPlaying()) {
					videoPlayUpToServer("1", mVideoView.getCurrentPosition()
							/ 1000 + "");
					msg = obtainMessage(SEND_LOG);
					sendMessageDelayed(msg, sLogTimeout);
				}
				break;
			}
		}
	};

	private boolean isShowing() {
		return mShowing;
	}

	// 获取播放位置
	public int getCurrentPosition() {
		if (mVideoView != null) {
			return mVideoView.getCurrentPosition();
		}
		return 0;
	}

	public void seekTo(int position) {
		if (mVideoView != null) {
			mVideoView.seekTo(position);
		}
	}

	public void pause() {
		if (mVideoView != null) {
			mPlaying = false;
			mPause = true;
			mVideoView.pause();
			Logger.i(TAG, "pause()");
		}
	}

	/**
	 * 释放资源
	 */
	public void release() {
		mRelease = true;
		mHandler.removeMessages(FADE_OUT);
		mHandler.removeMessages(SHOW_PROGRESS);
		mHandler.removeMessages(SHOW_PROGRESS_TWO);
		mHandler.removeMessages(CHECK_NET_WORK_CONNECTION);
		mHandler.removeMessages(SEND_LOG);
		if (mVideoView != null) {
			mVideoView.setVisibility(View.GONE);
			mVideoView.stopPlayback();
			mVideoView = null;
		}

		if (mRootView != null) {
			mRootView.invalidate();
			mRootView = null;
		}
		Logger.i(TAG, "release()");
	}
	
	

	private void resetVideoView() {
		mHandler.removeMessages(CHECK_NET_WORK_CONNECTION);

		if (mVideoView == null)
			return;
		if (!mPause) {
			mPause = false;
			mVideoView.setVideoURI(Uri.parse(mVideoUri));
		}
		if (mVideoView.getCurrentPosition() > 0) {
			mVideoView.seekTo(mVideoView.getCurrentPosition());
		}
		mVideoView.start();
		if (!TextUtils.isEmpty(mTitle)) {
			mTvTitle.setText(mTitle);
		} else {
			mTvTitle.setText("");
		}
		mIvPlay.setImageResource(R.drawable.btn_play_video_pause);
		mPlaying = true;
		mError = false;
	}
	
	public void resetStart(){
		mStop = false;
		mBufferingIndicator.setVisibility(View.GONE);
		if (!Helper.checkConnection(mCxt)) {
			mShowing = true;
			mLayShade.setVisibility(View.VISIBLE);
			mTvTitle.setText("视频源或网络错误");
		} else {
			if (!mError) {
				mVideoView.start();
				mIvPlay.setImageResource(R.drawable.btn_play_video_pause);
				mPlaying = true;
			} else {
				resetVideoView();
			}
		}
	}

	private void toggleMediaControlsVisiblity() {
		if (isShowing()) {
			hide();
		} else {
			show();
		}
	}

	private void hide() {
		showPlayProgress(true);
		mShowing = false;
		mLayShade.setVisibility(View.GONE);
	}

	private void show() {
		showPlayProgress(false);
		mShowing = true;
		mIvPlay.setVisibility(View.VISIBLE);
		mLayShade.setVisibility(View.VISIBLE);
		mHandler.sendEmptyMessage(SHOW_PROGRESS);
		mHandler.sendEmptyMessageDelayed(SEND_LOG, sLogTimeout);
		show(sDefaultTimeout);
	}
	
	private void videoPlayUpToServer(String flag,String time){
		if (!TextUtils.isEmpty(mVid)) {
			new NetEngine().videoPlayUpToServer(mCxt, mUuid, LoginInfo
					.getInstance().getUserId(), mVid, Constant.ADV_SOURCE_CLASSIFY, flag,time);
		}
	}

	private void showPlayProgress(boolean show) {
		if (show) {
			mHandler.removeMessages(SHOW_PROGRESS_TWO);
			mHandler.sendEmptyMessage(SHOW_PROGRESS_TWO);
		} else {
			mHandler.removeMessages(SHOW_PROGRESS_TWO);
		}
	}

	private void show(int timeout) {
		Message msg = mHandler.obtainMessage(FADE_OUT);
		if (timeout != 0) {
			mHandler.removeMessages(FADE_OUT);
			mHandler.sendMessageDelayed(msg, timeout);
		}
	}

	// 设置进度
	private int setProgress() {
		if (mDragging) {
			return 0;
		}
		int videoposition = mVideoView.getCurrentPosition();
		mTvBeginTime.setText(Utils.millisToString(videoposition));
		if (mSeekBar != null) {
			if (videoposition > 0) {
				mSeekBar.setProgress(videoposition);
			}

			int j = mVideoView.getBufferPercentage();
			int secondaryProgress = (j * mSeekBar.getMax() / 100);
			// 更新视频缓冲大小
			mSeekBar.setSecondaryProgress(secondaryProgress);
		}
		return videoposition;
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ScenarioVideoInfo videoInfo = new ScenarioVideoInfo(mVid, mVideoUri);
			if (videoInfo != null) {
				Intent intent = new Intent();
				intent.setClass(mCxt, PaikeVideoDetailActivity2.class);
				intent.putExtra("videoInfo", videoInfo);
				intent.putExtra("position", mVideoView.getCurrentPosition());
				intent.putExtra("isPause", !mPlaying);
				intent.putExtra("source", Constant.ADV_SOURCE_CLASSIFY);
				if (mParentFragment != null) {
					mParentFragment.startActivityForResult(intent,
							Constant.REQUESTCODE_FULL_SCREEN);
				} else {
					((BaseActivity) mCxt).startActivityForResult(intent,
							Constant.REQUESTCODE_FULL_SCREEN);
				}
			}
		}
	};

	/**
	 * 设置视频播放屏幕大小
	 * 
	 */
	private void setVideoPlayerSize() {

		int videoWidth = mVideoView.getVideoWidth();
		int videoHeight = mVideoView.getVideoHeight();
		int mWidth = WindowUtils.getScreenWidth(mCxt);
		double ar = (double) videoWidth / (double) videoHeight;
		int mHeight = (int) (mWidth / ar);
		LayoutParams mParams = mVideoPlayLayout.getLayoutParams();
		mParams.height = mHeight;
		mParams.width = mWidth;
		mVideoPlayLayout.setLayoutParams(mParams);
		mVideoView.setVideoScale(mWidth, mHeight);
	}
}
